<?php

include('cfg/def.php');
include('cfg/cfg.php');

include_once('lib/utils.class.php');
include_once('lib/timer.class.php');
$timer = new Timer('page', TRUE, FORMAT_S);

include_once('lib/logger.class.php');
Logger::$log_file = $log_file_name;

include_once('models/m_user.class.php');
include_once('models/m_city.class.php');
include('ctrl/page_plans.class.php');
include('ctrl/page_event.class.php');
include('ctrl/page_users.class.php');
include('ctrl/page_profile.class.php');
include('ctrl/page_messages.class.php');
include('ctrl/page_search.class.php');
include('ctrl/page_signup.class.php');
include('ctrl/page_errors.class.php');

header('Content-Type: text/html; charset=utf-8');

session_start();
Logger::Write(__FILE__." ".__FUNCTION__." line: ".__LINE__, "sid: ".session_id());

// В запросах полученных через AJAX будет проверяться этот параметр
$_SESSION["AJAXABLE"] = "YES";

// Logger::Write(__FILE__." ".__FUNCTION__." line: ".__LINE__, "SESSION: ".print_r($_SESSION, true));
// Logger::Write(__FILE__." ".__FUNCTION__." line: ".__LINE__, "FILES: ".print_r($_FILES, true));
// Logger::Write(__FILE__." ".__FUNCTION__." line: ".__LINE__, "SERVER: ".print_r($_SERVER, true));
Logger::Write(__FILE__." ".__FUNCTION__." line: ".__LINE__, "POST: ".print_r($_POST, true));
Logger::Write(__FILE__." ".__FUNCTION__." line: ".__LINE__, "GET: ".print_r($_GET, true));

// убираем случайный мусор вначале и в конце
foreach($_POST as $key=>$val) $_POST[$key] = trim($val);

// Посетитель
$actor = new mUser();

$cmd  = Utils::get_param('cmd', 'X');
if(strtoupper($cmd) == 'LOGOUT')
{
	$actor->logout();
	header('location: '.ROOT_URL);
}


// Авторизация

$actor->authorize();
// Для online проверки разных браузеров
// if(!$actor->is_authorized()) $actor->login('Aleksey@kogdakak.ru', 'АлексейX');

$actor->load();
$_SESSION['actor'] = $actor;

// Пользователь, события которого просматривают
$user = null;
$id = Utils::get_param("id", $actor->id);
if($id == 0) $id = $actor->id;

$_SESSION["url_id"] = $id;
$_SESSION["id2"] = Utils::get_param("id2", null);
$_SESSION["rule_id"] = Utils::get_param("rule_id", 0);
$_SESSION["page"] = strtolower(Utils::get_param("page", "plans"));
$_SESSION["categ"] = strtolower(Utils::get_param("categ", "own"));
$_SESSION["date"] = Utils::get_param("date", date("Y-m-d"));
if(!empty($_SESSION["categ"]))
	$_SESSION["categ"] = strtolower($_SESSION["categ"]);

set_city_to_session($actor);

// Logger::Write(__FILE__." ".__FUNCTION__." line: ".__LINE__, "SESSION: ".print_r($_SESSION, true));

$page = null;
switch($_SESSION["page"])
{
	case "plans":
		log_page("PagePlans");
		$_SESSION["categ"] = Utils::get_param("categ", "all");
		$user = new mUser($id);
		$user->load();
		$page = new PagePlans($actor, $user);
		break;
	
	case "event":
		log_page("PageEvent");
		$_SESSION["categ"] = Utils::get_param("categ", "comments");
		$page = new PageEvent($actor, $id);
		break;
	
	case "profile":
		log_page("PageProfile");
		
		if($actor->is_authorized())
		{
			if(!empty($_FILES))
			{
				$uploaddir = 'userpics/';
				$uploadfile = $uploaddir . basename($_FILES['face']['name']);
				$new_name = 'a-'.$actor->id.'-'.mktime().'.jpg';
				// Logger::Write(__FILE__." ".__FUNCTION__." line: ".__LINE__, "uploadfile: ".$uploadfile);
				// Logger::Write(__FILE__." ".__FUNCTION__." line: ".__LINE__, "new_name: ".$new_name);
				
				if(Utils::img_resize($_FILES['face']['tmp_name'], $uploaddir.$new_name, 48, 48))
				{
					$old_name = $actor->props["face"];
					$actor->update_avatar($new_name);
					if(substr($old_name, 0, 3) != "def")
						unlink($uploaddir.$old_name);
					header('location: '.$_SERVER["REQUEST_URI"]);
				}
			}
			elseif(!empty($_POST['update_user_info']))
			{
				$actor->update($_POST["username"], $_POST["city_id"], $_POST["male"], $_POST["born"], $_POST["note"]);
				header('location: '.$_SERVER["REQUEST_URI"]);
			}
			elseif(!empty($_POST['new_password']))
			{
				$actor->update_password($_POST['new_password']);
				header('location: '.$_SERVER["REQUEST_URI"]);
			}
			
			$page = new PageProfile($actor, null);
		}
		else
		{
			$page = new PageErrors($actor, null);
		}
		
		
		break;
	
	case "users":
		log_page("PageUsers");
		if($actor->is_authorized())
		{
			$_SESSION["categ"] = Utils::get_param("categ", "watch");
			$user = new mUser($id);
			$user->load();
			$user->load_users();
			$page = new PageUsers($actor, $user);
		}
		else
		{
			$page = new PageErrors($actor, null);
		}
		break;
	
	case "messages":
		log_page("PageMessages");
		$_SESSION["categ"] = Utils::get_param("categ", "all");
		if($id == $actor->id)
		{
			$user = $actor;
		}
		else
		{
			$user = new mUser($id);
			$user->load();
		}
		$page = new PageMessages($actor, $user);
		break;
	
	case "search":
		log_page("PageSearch");
		$page = new PageSearch($actor, $_POST['search']);
		break;
	
	case "signup":
		log_page("PageSignup");
		$page = new PageSignup($smtpurl);
		break;
	
	default:
		Logger::Write(__FILE__." ".__FUNCTION__." line: ".__LINE__, 'categ='.$_SESSION["categ"]);
		log_page("PageErrors");
		$page = new PageErrors($actor, null);
		break;
}

$page->out();
echo "\n<!-- ".$timer->stop()." sec -->";
Logger::Write(str_pad('-', 82, ' * -'), "");

function set_city_to_session($actor)
{
	// если ID города передано через URL,
	// то устанавливаем его
	if($_SESSION['rule_id'] == '6' &&
	   $_SESSION['page'] == 'plans' &&
	   Utils::get_param("categ", "all") == 'all')
	{
		$city = new mCity($_SESSION['id2']);
		if(!is_null($city->props))
		{
			$_SESSION['city_id'] = $_SESSION['id2'];
			$_SESSION['city'] = $city->props['city'];
		}
		else
		{
			$_SESSION['city_id'] = 0;
			$_SESSION['city'] = null;
		}
		setcookie('city_id', $_SESSION['city_id']);
		setcookie('city', $_SESSION['city']);
		return;
	}
	
	// иначе пытаемся получить 
	if(empty($_SESSION['city_id']))
	{
		if(empty($_COOKIE['city_id']))
		{
			$_SESSION['city_id'] = 0;
		}
		else
		{
			$_SESSION['city_id'] = $_COOKIE['city_id'];
			$_SESSION['city'] = $_COOKIE['city'];
		}
	}
}

function log_page($page_name)
{
	if(DEBUG_MODE)
		Logger::Write(__FILE__." ".__FUNCTION__." line: ".__LINE__, "page_name: $page_name");
}

